
import {
    request,
    WXshowToast,
    WXRedirectTo,
    WXNavigateTo,
    WXReLaunch
} from '../../utils/index.js';
import {
    Api,
    getWXPayOptions,
    requestPayment
} from '../../config/api.js';
const appInst = getApp();
const { imgBaseUrl, host, color } = appInst.globalData;

Page({
  data: {
    imgBaseUrl,
    host,
    color,
    addressList: [],
    // 默认地址
    addr:{},
    // [羊币，微信]
    payway: [true, false],
    goodlist: null,
    goodNum:null,
    totalMoney: 0,
    host:appInst.globalData.host
  },
  onLoad: function (options) {
     console.log(options)
    //  {goodid: "14", num: "1", gift: "礼包1:香怡肉块+香郁脊骨+养生汤骨", price: "1980", title: "尊享生活"}
     this.setData({
      options,
      // Api
     })
     console.log(this.data.options)
  },


    onShow:function(){
      
      if(wx.getStorageSync('dzactive')){//获取选中的地址 如没选中则调用默认收货地址
        let dzactive = wx.getStorageSync('dzactive')
        console.log('获取选中的地址 如没选中则调用默认收货地址')
        this.setData({
          addr:dzactive
        })
        wx.removeStorageSync('dzactive')
      }else{//否则调用默认收货地址
        this._getAddressList()
        console.log('否则调用默认收货地址')
      }

      if(wx.getStorageSync('gmtype')){//如果有商品类型 则写入页面
        this.setData({
          gmtype:wx.getStorageSync('gmtype')
        })
        wx.removeStorageSync('gmtype')
      }
      
        // this.getGood()
    },

    // 获取商品想详情
    getGood(){
        let goodlist = wx.getStorageSync("goodlist");
        let totalMoney = 0
        let goodNum = 0
        if(goodlist.length>1){
             goodlist.forEach((item) => {
                
                 totalMoney += item.num * Number(item.price)
                 goodNum += item.num
             })
        }else{
            totalMoney = goodlist[0].price
            goodNum =1
        }

        this.setData({
            goodlist,
            totalMoney, 
            goodNum
        })
    },




  // 计算 scroll-view 高度
  calcScrollViewHeight() {
      const otherElArr = ['#handler']
      calcScrollViewHeight(otherElArr, this, 12).then(res => {
          this.setData({
              scrollViewHeight: res
          })
      })
  },

    // switch 开关
  changePayWay(e) {
    const { index } = e.currentTarget.dataset
    const { value } = e.detail


    this.setData({  
      payway: this.data.payway.map((item, idx) => {
        if (idx === index) return value

        return !value
      })
    })
  },


//   获取收货地址
async  _getAddressList() {
      const {data} = await request({
          url: Api.getAddressList,
            method: 'POST'
      })

       data.data.map((item,index)=>{
         if(item.state === 1){
           this.setData({
             addr:item
           })
         }
       })
    this.setData({
        addressList: data.data,
    })
  },


  
  async js(){//去结算
     let that = this
     const {
      totalMoney,
     deduction,
     addr
} = this.data
console.log(this)
console.log(addr)
if (!Object.keys(addr).length) {
  WXshowToast("请选择收货地址")
  setTimeout(() => {
      WXNavigateTo("/pages/select_addr/select_addr")
  }, 500)
  return
}
    // let  address_id = (()=>{
    //   //  console.log(this.data.addr.id)
    //     // if(that.data.addr.id){
    //     //   return  that.data.addr.id
    //     // }else{
    //     //   WXshowToast('未填写收获地址')
    //     // }
    //  })();
     const openid = wx.getStorageSync("openid")
     const {options} = that.data
      console.log(options)
     const {price} = options//价格
     let goods_id = options.goods_id//商品ID
     console.log('goods_id',goods_id)
      let pay_num = options.num//购买数量
      let coupon_id = options.id//礼品id
      let address_id = addr.id//收货地址
    
    console.log('price',price)
    // console.log('pay_num',pay_num)
    // console.log('gift_bag',gift_bag)
    //  const goodlist  =wx.getStorageSync("goodlist")
     let money,order_no,pay
    // switch(this.data.gmtype){
    //   case 1:

      
         money = 29.9  //总价格
         order_no =options.order_sn //订单编号
         console.log(money)
         console.log(order_no)

      pay =  await   getWXPayOptions({
                money,
                title:"红酒兑换",
                order_no,
                openid,
                address_id
       })
      // 发起微信支付
         try {
             const src = await requestPayment(pay.data.data.wx_pub);
             let content = '恭喜，兑换成功'
              wx.showModal({
                // title,
                showCancel: false,//是否显示取消按钮
                  confirmText:"我知道了",
                content,
                success: function (res) {
                  // resolve(res)
                  WXReLaunch('/pages/index/index')
                },
                fail: function (err) {
                  // reject(err)
                },
              })
            //  WXRedirectTo(`/pages/choujiang/choujiang?address_id=${addr.id}`)
         } catch (err) {
             wx.showToast({
                 title: '支付取消',
                 icon: 'none',
             });
         }
      
      // break;
    
      // case 2:
      //   console.log("从购物车来的")
      //   let cart_id = []
      //   for(var i =0; i<goodlist.length;i++){
      //       cart_id.push(goodlist[i].id)
      //   }
      //  cart_id= cart_id.toString()
      //   const res = await request({
      //        url: Api.cartAll,
      //         method: 'POST',
      //         data:{
      //             address_id,
      //             cart_id
      //         }
      //   })  
          
      //      money = Object.values(res.data.data)[1]  //总价格
      //      order_no = Object.values(res.data.data)[0][0].order_sn //订单编号
      //      pay =  await   getWXPayOptions({
      //                 money,
      //                 title:"肉串礼盒",
      //                 order_no,
      //                 openid
      //        })
      //       // 发起微信支付
              //  try {
              //      const src = await requestPayment(pay.data.data.wx_pub);
              //  } catch (err) {
              //      wx.showToast({
              //          title: '支付取消',
              //          icon: 'none',
              //      });
              //  }
    // }       
  },
  handleChangeCount(e){
    let num = parseInt(this.options.num) 
    let num2 = num+1
    console.log(num2)
    let num1 = 'options.num'
    // this.setData({
    //   [num1]:num
    // })
    // console.log(1)

    // const { step} = e.currentTarget.dataset
    // if (step < 0) {
    //   if (Number(this.data.options.num) === 1) {
    //     WXShowModal('提示', '您想要从购物车中删除该商品吗？').then(res => {
    //       if (res.confirm) {
    //         // 删除 ajax
    //         this.setData({
    //           goodlist:[]
    //         })
    //       }
    //     })
    //   } else {
    //     // 减数量 ajax
    //     let num = Number(this.data.options.num)+step
    //     this.setData({
    //       ...options,
    //       num
    //     })
    //   }
    // } else {
    //   // 加数量 ajax
    //   console.log(this.data.options.num)
    //   let num = Number(this.data.options.num)+step
    //   this.setData({
    //     ...options,
    //     num
    //   })
    // }
  }
})